<template>
  <div v-show="!loading" class="page-box">
    <div class="item-box  article-box" v-if="articleInfo">
      <div class="title">{{articleInfo.title}}</div>
      <div class="info-box">
        <div class="left">
          <img :src="articleInfo.avatar">
        </div>
        <div class="middle">
          <span>{{articleInfo.author}}</span>
          <div>
            <span>{{dateFormat(articleInfo.createTime,'yyyy/MM/dd')}}</span>
            <span>·</span>
            <span>点赞 {{articleInfo.praise}}</span>
          </div>
        </div>
        <div v-if=" followedFlag !== null " class="right" :class="[{followed: followedFlag}, {top: isAndriodFlag}]" @click="follow(articleInfo.userId)">{{followedFlag? '已关注': '关注'}}</div>
      </div>
      <div class="short-content">
        <span class="red">摘要：</span>
        <span>{{articleInfo.summary}}</span>
      </div>
      <div class="cover">
        <img v-if="articleInfo.imgUrl" :src="articleInfo.imgUrl">
      </div>
      <div class="detail" v-html="articleInfo.details"></div>
      <div class="up-rewoard-box">
        <div>
          <div class="img-box" @click="up()" v-if="articleInfo.isPraise===0">
            <img src="../assets/up.png">
          </div>
          <div class="img-box" v-else>
            <img src="../assets/uped.png">
          </div>
          <div>赞</div>
        </div>
        <div>
          <div class="img-box" @click="ctrlRewardAmountBox(true)">
            <img src="../assets/reward.png">
          </div>
          <div>打赏</div>
        </div>
      </div>
      <div class="reward-list-box">
        <template v-if="rewardList.length > 0">
          <div class="reward-avatar-box">
            <div :style="{ width: rewardList.length * 30 + 'rem' }">
              <template v-for="(item, index) in rewardList">
                <img v-if="index < 3" :style="{ left: index * 20 + 'rem' }" :key="index" :src="item.payerUserAvatar" />
              </template>
            </div>
          </div>
          <span>{{rewardList.length > 3? '等': ''}}</span>
          <span class="num">{{rewardList.length}}</span>
          <span>人已打赏</span>
        </template>
        <template v-else>
          <span>首席赞赏官虚位以待</span>
        </template>
      </div>
      <div class="reward-amount-box" v-show="rewardAmountBoxFlag">
        <div class="main">
          <div class="reward-title">
            <span>打赏</span>
            <span class="close-btn" @click="ctrlRewardAmountBox(false)">×</span>
          </div>
          <div class="amount-box">
            <div class="amount-box-item">
              <template v-for="(item, index) in amountArr">
                <div v-if="index < 3" :key="item" class="amount-item" :class="{'on': amountSelected === item}" @click="selectAmount(item)">
                  <div class="coin"></div>
                  <label>{{item}}</label>
                </div>
              </template>
            </div>
            <div class="amount-box-item">
              <template v-for="(item, index) in amountArr">
                <div v-if="index > 2" :key="item" class="amount-item" :class="{'on': amountSelected === item}" @click="selectAmount(item)">
                  <div class="coin"></div>
                  <label>{{item}}</label>
                </div>
              </template>
            </div>
          </div>
          <div class="custom-amount">
            <input type="number" class="input-box" placeholder="自定义金额" v-model="inputAmount" @focus="inputFocus()">
            <div :class="{'disabled':amountSelected < 0 && inputAmount === ''}" @click="doReward()">打赏</div>
          </div>
        </div>
      </div>
      <div class="tips">
        文章内容仅供参考，不构成投资建议，投资有风险，入市需谨慎！
      </div>
      <div class="keyword-box">
        <template v-if="articleInfo.keyword">
          <span v-for="item in articleInfo.keyword.split(',')" :key="item">{{item}}</span>
        </template>
      </div>
    </div>
    <Recommend v-if="recommendList.length > 0" class="item-box" :list="recommendList" type="viewpoint"/>
  </div>
</template>

<script>
import * as api from '@/utils/api'
import { dateFormat } from '@/utils/date'
import cookie from '@/utils/cookie'
import { operationType } from '@/utils/assist'
import { Toast, Indicator } from 'mint-ui'
import { getToken, setToken } from '@/utils/auth'
import Recommend from '@/components/recommend-article'
export default {
  name: 'index',
  components: {
    Recommend
  },
  data () {
    return {
      loading: true,
      followedFlag: null,
      isAndriodFlag: false,
      articleInfo: {},
      rewardList: [],
      rewardAmountBoxFlag: false,
      amountArr: [10, 20, 50, 66, 88, 100],
      inputAmount: '',
      amountSelected: 10,
      deviceType: null,
      siteId: process.env.NODE_ENV === 'production' ? '123504' : '123530',
      recommendList: []
    }
  },
  watch: {
    '$route' (to, val) {
      this.id = this.$route.params.id
      this.initData()
      return val
    }
  },
  created () {
    this.id = this.$route.params.id
    document.title = '文章详情'
    this.getTokenFromApp()
    this.initFnForApp()
  },
  methods: {
    dateFormat: dateFormat,
    ctrlRewardAmountBox (flag) {
      this.rewardAmountBoxFlag = flag
    },
    selectAmount (item) {
      this.amountSelected = item
    },
    inputFocus () {
      this.amountSelected = -1
    },

    doReward () {
      let amount = 0
      if (this.amountSelected > -1) {
        amount = this.amountSelected
      } else {
        amount = this.inputAmount
      }
      let reg = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/
      if (!reg.test(amount)) {
        Toast('请输入正确的金额')
        return
      }
      let rewardInfo = {
        amount: amount,
        businessId: this.$route.params.id,
        type: 'app',
        siteId: this.siteId
      }
      this.sendRewordInfoToApp(rewardInfo)
    },
    sendRewordInfoToApp (rewardInfo) {
      let str = JSON.stringify(rewardInfo)
      if (this.deviceType.android) {
        if (typeof window.androidApp !== 'undefined') {
          window.androidApp.pay(str)
        } else {
          Toast('window.androidApp 不存在')
        }
      } else {
        if (typeof window.iosApp !== 'undefined') {
          window.iosApp.pay(str)
        } else {
          Toast('window.iosApp 不存在')
        }
      }
    },

    async up () {
      try {
        let res = await api.praiseForViewpointArticle({
          viewPointId: this.id,
          isPraise: 1,
          siteId: this.siteId
        })

        if (!res) {
          this.articleInfo.isPraise = 1
        }
      } catch (error) {
        Toast('操作失败，' + error.message)
      }
    },

    async follow (userId) {
      let params = {
        siteId: this.siteId,
        focusUserId: userId,
        focusStatus: this.followedFlag ? 0 : 1 // 1表示取消关注
      }
      try {
        let res = await api.focusUser(params)
        if (res.data) {
          let arr = ['关注失败']
          if (res.data.message) {
            arr.push(res.data.message)
          }
          Toast(arr.join(','))
        } else {
          if (this.followedFlag) {
            Toast('取消成功')
          } else {
            Toast('关注成功')
          }
          this.followedFlag = !this.followedFlag
        }
      } catch (error) {
        Toast('操作失败,' + error.message)
      }
    },
    /**
     * 初始化页面数据
     */
    initData () {
      Indicator.open()
      this.loading = true
      Promise.all([
        this.getArticleInfo(),
        this.getRewardRecordData(),
        this.getRecommendArticleInfo()
      ]).then((res) => {
        let articleData = res[0]
        if (articleData && articleData.code === 200) {
          this.articleInfo = articleData.data
          this.getFocusStatus()
        }
        let rewardData = res[1]
        if (rewardData) {
          this.rewardList = rewardData
        }
        let recommendData = res[2]
        if (recommendData) {
          let tempList = recommendData.data.list
          let index = tempList.findIndex((item) => {
            return item.viewPointId + '' === this.id
          })
          if (index >= 0) {
            tempList.splice(index, 1)
          }
          this.recommendList = tempList
        }
        Indicator.close()
        this.loading = false
      }).catch((e) => {
        Indicator.close()
        console.log(e)
      })
    },

    /***
     * 文章信息
     */
    async getArticleInfo () {
      try {
        const id = this.$route.params.id
        let params = {
          viewPointId: id,
          siteId: this.siteId
        }
        let res = await api.getArticleDetailForViewpoint(params) // 观点文章
        return res
      } catch (error) {
        Toast('数据加载失败,' + error.message)
      }
    },
    async getFocusStatus () {
      try {
        let params = {
          userId: '',
          focusUserId: this.articleInfo.userId,
          siteId: this.siteId
        }
        let res = await api.getFocusStatus(params) // 是否关注了作者
        this.followedFlag = res.focusStatus === 1
      } catch (error) {
        Toast('关注数据加载失败,' + error.message)
      }
    },
    /**
     * 打赏信息
     */
    async getRewardRecordData () {
      try {
        let res = await api.articleRewardRecord(this.id, { siteId: this.siteId }) // 观点文章
        return res
      } catch (error) {
        Toast('操作失败,' + error.message)
      }
    },
    // 推荐文章列表
    async getRecommendArticleInfo () {
      try {
        let params = {
          data: {
            siteId: this.siteId
          },
          pageTo: {
            pageNum: 1,
            pageSize: 10
          }
        }
        let res = await api.getViewpointRecommendArticle(params) // cms文章
        return res
      } catch (error) {
        Toast('数据加载失败，' + error.message)
      }
    },

    // 调用app的方法获取token
    getTokenFromApp () {
      this.deviceType = operationType()
      let token = null
      if (this.deviceType.mobile) {
        if (this.deviceType.android) {
          this.isAndriodFlag = true
          if (typeof window.androidApp !== 'undefined') {
            token = window.androidApp.getToken()
            this.setTokenAndCookie(token)
          }
          this.initData()
        } else {
          setTimeout(() => {
            if (typeof window.iosApp !== 'undefined') {
              window.iosApp.getToken()
            } else {
              this.initData()
            }
          }, 500)
        }
      } else {
        if (!getToken()) {
          token = 'fake test token'
          this.setTokenAndCookie(token)
        }
        this.initData()
      }
    },
    initFnForApp () {
      window.rewardSuccess = () => {
        Toast('打赏成功')
        this.rewardAmountBoxFlag = false
        this.getRewardRecordData().then((res) => {
          if (res && res.code === 200) {
            this.rewardList = res.data
          }
        })
      }
      window.rewardFail = (res) => {
        Toast('打赏失败' + res)
      }
      window.receiveTokenFromIOS = (token) => {
        this.setTokenAndCookie(token)
        this.initData()
      }
    },
    setTokenAndCookie (token) {
      cookie.set('device_id', token)
      setToken(token)
    },
    // 分享
    shareTopic () {
      let url = window.location.href
      let title = this.data.title
      if (this.deviceType.mobile) {
        if (this.deviceType.android) {
          if (typeof window.androidApp !== 'undefined') {
            window.androidApp.shareTopic(url, title)
          } else {
            Toast('window.androidApp 不存在')
          }
        } else {

        }
      }
    }
  }
}
</script>
<style lang="scss" scope>
@import "../style/art-detail";
</style>
